package com.xm.storage.utils;

import com.influxdb.client.InfluxDBClient;
import com.influxdb.client.InfluxDBClientFactory;
import com.influxdb.client.WriteApiBlocking;
import com.influxdb.client.domain.WritePrecision;
import com.xm.common.entity.dto.Client;
import com.xm.common.entity.vo.request.RuntimeDetailVO;
import com.xm.storage.entiry.RuntimeData;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class InfluxDbUtils {

    @Value("${spring.influx.my-url}")
    String url;
    @Value("${spring.influx.my-user}")
    String user;
    @Value("${spring.influx.my-password}")
    String password;

    private final String BUCKET = "monitor";
    private final String ORG = "xm";
    private final String TOKEN = "ucq2xUTjY0YA2UGrPPZvTFIi7KVrtYBe1cp7IoIJutLqSXXiRwnOAgSrTLxRTfZQKCQ1_mfbhBQYOdGVIQo5IQ==";

    private InfluxDBClient client;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public Client findClientByToken(String token) {
        return (Client) redisTemplate.opsForHash().get("clientTokenCache", token);
    }

    public void updateRuntimeDetail(RuntimeDetailVO vo, Client client) {
        redisTemplate.opsForHash().put("currentRuntime", String.valueOf(client.getId()), vo);
        this.writeRuntimeData(client.getId(), vo);
    }

    @PostConstruct
    public void init() {
        client = InfluxDBClientFactory.create(url, user, password.toCharArray());
    }

    public void writeRuntimeData(int clientId, RuntimeDetailVO vo) {
        RuntimeData data = new RuntimeData();
        BeanUtils.copyProperties(vo, data);
        data.setTimestamp(new Date(vo.getTimestamp()).toInstant());
        data.setClientId(clientId);
        WriteApiBlocking writeApi = client.getWriteApiBlocking();
        writeApi.writeMeasurement(BUCKET, ORG, WritePrecision.NS, data);
    }
}
